class Statistics::Reply
  include Mongoid::Document

  # has_many :push_histories

  field :new_replies, :type => Array, :default => []
  field :replies, :type => Array, :default => []
  field :since_id, :type => String
  field :refresh_time, :type => Time, :default => Time.now
  belongs_to :account

  def refresh
    nr = []
    return new_replies if Time.now - self.refresh_time < 30.minutes
    # ph_ids = account.tasks.map{ |task| task.push_histories.map(&:_id) }

    Utility::Weibo.active.all.each do |spammer|
      result = spammer.mentions(since_id || '0')
      if result["error"].present?
        next
      else
        result["statuses"].each_with_index do |tweet, index|
          _mid = Utility.get_j("http://api.t.sina.com.cn/querymid.json?id=#{tweet["id"]}&type=1")["mid"]
          result["statuses"][index]["wurl"] = "http://weibo.com/#{tweet["user"]["id"]}/#{_mid}" if _mid.present?
          result["statuses"][index]["user_url"] = "http://e.weibo.com/#{tweet["user"]["id"]}"
        end
        nr += result["statuses"]
      end
    end
    if nr.present?
      self.replies.insert(0, new_replies)
      self.new_replies = nr
      self.since_id = nr.first["id"].to_s
    end
    self.refresh_time = Time.now
    self.save
    new_replies
  end

  def add(reply, uid, wid)
    spammer = Utility::Weibo.where(:uid => uid).active.first ||
        Utility::Weibo.get_spammer
    return false unless spammer
    spammer.add_comment(reply, wid, uid)
  end

end